<template>
	<el-dialog v-model="visible" :title="!dataForm.deviceId ? '新增' : '修改'" :close-on-click-modal="false">
		<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="100px" @keyup.enter="submitHandle()">
			<el-form-item label="设备ID" prop="deviceId">
				<el-input v-model="dataForm.deviceId" placeholder="设备ID"></el-input>
			</el-form-item>
			<el-form-item label="设备名字" prop="deviceName">
				<el-input v-model="dataForm.deviceName" placeholder="设备名字"></el-input>
			</el-form-item>
			<el-form-item label="设备所有者" prop="deviceOwner">
				<el-input v-model="dataForm.deviceOwner" placeholder="设备所有者"></el-input>
			</el-form-item>
			<el-form-item label="设备编号" prop="deviceNumber">
				<el-input v-model="dataForm.deviceNumber" placeholder="设备编号"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" @click="submitHandle()">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus/es'
import {editDevice, useDeviceApi, useDeviceSubmitApi} from '@/api/clouddevice/device.ts'

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const dataFormRef = ref()

let dataForm = reactive({
	deviceId: '',
	deviceName: '',
	deviceOwner: '',
	deviceNumber: '',
	deleted: '',
	createTime: '',
	updateTime: '',
	createor: '',
	updater: ''
})

const init = (id?: number) => {
	visible.value = true
	dataForm.deviceId = ''

	// 重置表单数据
	if (dataFormRef.value) {
		dataFormRef.value.resetFields()
	}
  console.log("打印id :",id)
	if (id) {
		getDevice(id)
	}
}

const getDevice = (id: number) => {
  dataForm.deviceId = String(id)
  console.log("查看表单内容",dataForm)
	useDeviceApi(JSON.stringify(dataForm)).then(res => {
		Object.assign(dataForm, res.data)
	})
}

const dataRules = ref({})

// 表单提交
const submitHandle = () => {
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			return false
		}
    editDevice([dataForm]).then(() => {
			ElMessage.success({
				message: '操作成功',
				duration: 500,
				onClose: () => {
					visible.value = false
					emit('refreshDataList')
				}
			})
		})
	})
}

defineExpose({
	init
})
</script>
